package com.kaisu.blog.infrastructure.file.repository.impl;

import com.kaisu.blog.common.exceptions.InternalException;
import com.kaisu.blog.domain.file.File;
import com.kaisu.blog.domain.file.repository.FileRepository;
import com.kaisu.blog.domain.storage.Storage;
import com.kaisu.blog.infrastructure.file.FilePO;
import com.kaisu.blog.infrastructure.file.convert.FileConvert;
import com.kaisu.blog.infrastructure.file.dao.FilePODAO;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Optional;

/**
 * @author kaisu
 */
@Repository
public class FileRepositoryImpl implements FileRepository {
    private final Storage storage;
    private final FilePODAO filePODAO;
    private final FileConvert fileConvert;

    public FileRepositoryImpl(@Qualifier("localStorage") Storage storage, FilePODAO filePODAO, FileConvert fileConvert) {
        this.storage = storage;
        this.filePODAO = filePODAO;
        this.fileConvert = fileConvert;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upload(InputStream fileStream, File file) {
        storage.upload(fileStream, file);
        filePODAO.save(fileConvert.toPO(file));
    }

    @Override
    public File findById(String id) {
        Optional<FilePO> filePO = filePODAO.findById(id);
        File file = filePO.map(fileConvert::toDomain).orElseThrow(() -> new InternalException("没有找到指定的文件！"));
        file.setStoragePath(storage.getPath(file));
        file.setPreviewPath(storage.getPreviewPath(file));
        return file;
    }
}
